<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-03-03 20:56:45
 * @Description  : 添加用户到部门
-->

<template>
  <!-- <n-card
    :size="'small'"
    style="width: 768px"
    role="dialog"
    title="添加用户到部门"
    :bordered="false"
    aria-modal="true"
  >
    <template #header-extra>
      <SvgIcon
        icon="chacha"
        class="cursor-pointer"
        @click="handleClose"
      ></SvgIcon>
    </template>
    <n-divider class="!my-2" /> -->
  <n-form
    ref="addUserToDepFormRef"
    :label-width="isSmall ? 100 : 120"
    label-placement="left"
    :label-align="isSmall ? 'left' : 'right'"
    :model="user"
    size="small"
    require-mark-placement="right"
    :rules="formRule"
  >
    <n-form-item label="已选用户：" path="userIds">
      <UserSelect
        :has-not-dep-user="false"
        :root-dep-id="rootDep.id"
        :default-user-ids="user.userIds"
        @change-value="handleUserIdsChange"
        class="!w-[300px]"
      ></UserSelect>
    </n-form-item>

    <n-form-item label="所在部门：">
      <auth-table
        @change-default-role-id="handleChangeDefaultRoleId"
        class="w-full"
        :target-list="targetList"
        @change-target-list="handleChangeTargetList"
        @change-default-size-max="handleChangeDefaultSizeMax"
      ></auth-table>
    </n-form-item>
    <n-form-item label=" " path="defaultSizeMax">
      <n-popselect
        trigger="click"
        :options="[]"
        class="w-[300px]"
        display-directive="show"
        placement="right"
      >
        <template #header>
          <dep-select
            :root-dep="rootDep"
            @change-value="handleDepChange"
            :default-dep-ids="targetList.map((item) => item.id)"
          ></dep-select>
        </template>
        <template #empty> <div></div> </template>
        <n-button type="tertiary" class="text-[13px]">
          <svg-icon icon="tianjiatianjiayonghu11" class="mr-1"></svg-icon>
          添加部门
        </n-button>
      </n-popselect>
    </n-form-item>

    <n-form-item label=" " v-permission="[PERMISSIONS.USER_EDIT]">
      <n-button type="primary" class="grent-btn w-[120px]" @click="handleSave">
        保存
      </n-button>
    </n-form-item>
  </n-form>
  <!-- </n-card> -->
</template>

<script setup lang="ts">
import type { FormInst } from 'naive-ui'
import type { UserDepCopyReq } from '@/types/userDep'
import { userMenuShow } from '@/hooks/useMenuShow'
import { PERMISSIONS } from '@/constants/permission'
import type { IndexObj } from '@/types/commom'

const emits = defineEmits<{
  (e: 'visibleChange', value: boolean): void
  (e: 'addUserToDep', data: UserDepCopyReq): void
}>()

const props = defineProps<{
  checkUserIds: string[]
  rootDep?: any
}>()

const handleClose = () => {
  emits('visibleChange', false)
}

const { isSmall } = userMenuShow()

const user = reactive<UserDepCopyReq>({
  departments: [],
  userIds: []
})

const targetList = ref<IndexObj[]>([])
const authTableDefaultRoleId = ref('4')
const authTableDefaultSizeMax = ref('0')

const initUser = () => {
  user.userIds = props.checkUserIds
  user.departments = []
}

onMounted(() => {
  initUser()
})

const handleChangeDefaultRoleId = (value: string) => {
  authTableDefaultRoleId.value = value
}

const handleChangeDefaultSizeMax = (value: string) => {
  authTableDefaultSizeMax.value = value
}

const handleChangeTargetList = (list: IndexObj[]) => {
  targetList.value = list
}

// 添加部门时发生发生改变，选择的部门发生了改变
const handleDepChange = (value: string | string[], depsInfo: IndexObj[]) => {
  // 选择的对象发生了改变，[a,b,c]---->[a,b,f,g,h]
  // 权限信息同步修改，a，b的暂时不需要变更（authRolen）

  // targetList保留 value还在的，其他删除
  // target原先没有的，进行添加

  targetList.value = targetList.value.filter((item) => {
    return value.includes(item.id)
  })

  // target现在没有的
  let moreTargets = depsInfo
    .filter((item) => {
      return !targetList.value.some((item2) => {
        return item2.id === item.id
      })
    })
    .map((item3) => {
      return {
        sizeMax: authTableDefaultSizeMax.value,
        authRole: authTableDefaultRoleId.value,
        ...item3,
        targetName: item3.name,
        pTargetName: item3.parent.name
      }
    })

  targetList.value = targetList.value.concat(moreTargets)
}

const handleUserIdsChange = (value: string[] | string) => {
  user.userIds = value as string[]
}

const formRule = {}

const addUserToDepFormRef = ref<FormInst | null>(null)

const handleSave = () => {
  addUserToDepFormRef.value?.validate((error: any) => {
    if (error) {
      return
    }

    emits('addUserToDep', {
      departments: targetList.value.map((item) => {
        return {
          departmentId: item.id,
          sizeMax: item.sizeMax,
          roleId: item.authRole
        }
      }),
      userIds: user.userIds
    })
  })
}
</script>

<style scoped lang="scss"></style>
